//
//  HZTabBar.swift
//  HansWeibo
//
//  Created by Hans on 16/8/9.
//  Copyright © 2016年 Hans. All rights reserved.
//

import UIKit
//声明协议  需要继承NSObjectProtocol
protocol HZTabBarDelegate:NSObjectProtocol {
    //声明代理方法
    func tabBarButtonClick()
}

class HZTabBar: UITabBar {

   // 声明一个代理
    weak var HZDelegate:HZTabBarDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // MARK: - 监听方法
    func buttonClick(){
        
        HZDelegate?.tabBarButtonClick()
        
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        addSubview(middleButton)
    }
    
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //子控件的宽度
        let W = self.frame.width / 5
        var index: CGFloat = 0
        //遍历子控件
        for value in self.subviews {
            //NSClassFromString 通过字符串转Class 
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!){
                //设置frame
                value.frame.size.width = W
                value.frame.origin.x = index * W
                index++
                if index == 2 {
                    index++
                }
            }
            
        }
        //设置中间按钮的frame
        middleButton.center.x = self.frame.width/2
        middleButton.center.y = self.frame.height/2
        
    }

    // MARK: - 懒加载控件
    private lazy var middleButton: UIButton = {
        let button = UIButton()
        //点击事件
        button.addTarget(self, action: #selector(HZTabBar.buttonClick), forControlEvents: UIControlEvents.TouchUpInside)
        
        
        //设置背景图片
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button"), forState: UIControlState.Normal)
        //设置图片
        button.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        button.setImage(UIImage(named:"tabbar_compose_icon_add"), forState: UIControlState.Normal)
        //自适应
        button.sizeToFit()
        return button
    }()
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
